<template>
  <div class="info-attr-module">
    <div class="title">基本信息</div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px" class="term-ruleForm"
      :size="formSize" status-icon>
      <div class="register">
        <div class="item">
          <div class="name">所属地区</div>
          <div class="right">
            <div class="text">{{ ruleForm.provinceName }} {{ ruleForm.cityName }}</div>
          </div>
        </div>
        <div class="item">
          <div class="name"><span>*</span>代表队名称</div>
          <div class="right">
            <input v-model.trim="ruleForm.teamName" placeholder="请输入" />
          </div>
        </div>
        <div class="item">
          <div class="name"><span>*</span>代表队负责人</div>
          <div class="right">
            <input v-model.trim="ruleForm.realName" placeholder="请输入" />
          </div>
        </div>
        <div class="item">
          <div class="name"><span>*</span>联系方式(手机)</div>
          <div class="right">
            <input v-model.trim="ruleForm.phone" placeholder="请输入" class="phone" /><span class="code"
              @click="queryUser">查询手机号</span>
          </div>
        </div>
        <div class="item">
          <div class="name">性别</div>
          <div class="right">
            {{ ruleForm.sex ? (ruleForm.sex === '1' ? '男' : '女') : '' }}
          </div>
        </div>
        <div class="item">
          <div class="name">证件类型</div>
          <div class="right">
            {{ ruleForm.idType === '1' ? '居民身份证' : ruleForm.idType === '2' ? '临时身份证' : ruleForm.idType === '3' ?
              '港澳居民来往内地通行证' : ruleForm.idType === '4' ? '台湾居民来往大陆通行证' : ruleForm.idType === '5' ? '护照/其他' : ''}}
          </div>
        </div>
        <div class="item">
          <div class="name">证件号码</div>
          <div class="right">
            {{ baseService.hideIdCard(ruleForm.idCard) }}
          </div>
        </div>
        <div class="item">
          <div class="name">参赛单位</div>
          <div class="right">
            {{ ruleForm.company }} <span class="code" v-if="ruleForm.updComTimes == 0"
              @click="reAuthVisible = true">更新单位名称</span>
          </div>
        </div>
        <div class="item">
          <div class="name">电子邮箱</div>
          <div class="right">
            <input v-model.trim="ruleForm.email" placeholder="请输入" />
          </div>
        </div>

        <div class="item upload">
          <div class="name">一寸证件照</div>
          <el-upload disabled class="avatar-uploader" :action="baseUrl + '/front/upload'" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <div class="image">
              <img v-if="imageUrl" :src="imageUrl" class="img" />
              <div v-else class="upload">
                <img src="@/assets/upload.png">
              </div>
            </div>
          </el-upload>
        </div>
        <div class="item upload">
          <div class="name">负责人授权书(单位盖章)</div>
          <el-upload class="avatar-uploader" :action="baseUrl + '/front/upload'" :show-file-list="false"
            :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2">
            <div class="image">
              <img v-if="imageUrl2" :src="imageUrl2" class="img" />
              <div v-else class="upload">
                <img src="@/assets/upload.png">
              </div>
            </div>
          </el-upload>
        </div>
      </div>
      <div style="height: 10rem"></div>
      <div class="fixed-btn">
        <input type="button" class="btn" @click="submitForm(ruleFormRef)" value="提交" />
      </div>
    </el-form>
  </div>
  <!--抽签弹窗-->
  <el-dialog v-model="reAuthVisible" :show-close="false" width="90%">
    <div class="confirm-dialog">
      <el-form ref="reAuthFormRef" :model="reAuthForm" label-width="12rem" class="term-ruleForm" :size="formSize"
        status-icon>
        <el-form-item label="参赛单位">
          <el-input v-model.trim="reAuthForm.company" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="统一社会信用代码">
          <el-input v-model.trim="reAuthForm.companyNo" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div class="btns">
        <el-button @click="reAuthVisible = false">关闭</el-button>
        <el-button type="primary" v-loading="reAuthForm.loading" @click="reAuthCompany()">确认</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import app from "@/constants/app";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps } from 'element-plus'
import baseService from "@/service/baseService";
import { useRouter } from "vue-router";
import { removeCache } from "@/utils/cache";
import { ElMessage, ElMessageBox } from "element-plus";
const imageUrl = ref('')
const imageUrl2 = ref('')
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const baseUrl = app.api;
let router = useRouter();
const ruleForm = reactive({
  id: null,
  email: "",
  company: "",
  provinceName: '',
  cityName: '',
  companyNo: '',
  realName: '',
  sex: "",
  idType: "",
  idCard: "",
  phone: "",
  code: "",
  teamName: "",
  header: "",
  empower: "",
  oldEmpower: "",
  leaderId: null,
  oldLeaderId: null,
  creator: "",
  updComTimes: 0
});

const reAuthForm = reactive({
  id: null,
  companyNo: "",
  company: "",
  loading: false,
});

const rules = reactive<FormRules>({
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  company: [{ required: true, message: "请输入参赛单位", trigger: "blur" }],
  //province: [{ required: true, message: "请选择地区", trigger: "change" }],
  companyNo: [{ required: true, message: "请输入执照", trigger: "blur" }],
  realName: [{ required: true, message: "请输入领队姓名", trigger: "blur" }],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  idType: [{ required: true, message: "请选择证件", trigger: "change", }],
  idCard: [{ required: true, message: "请输入证件号码", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});
const reAuthVisible = ref(false);
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // 如果领队有更改过, 则跳转到领队创建页面, 否则跳转到代表队页面
  if (ruleForm.leaderId != ruleForm.oldLeaderId) {
    // 授权书必须重新上传
    if (ruleForm.empower == ruleForm.oldEmpower) {
      ElMessage.error("请重新上传授权书");
      return;
    }
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      baseService
        .post("/front/spteam/update", ruleForm)
        .then((res) => {
          if (res.code === 0) {
            ElMessage.success("修改成功, 请重新登录");
            // 如果领队有更改过, 则跳转到领队创建页面, 否则跳转到代表队页面
            if (ruleForm.leaderId != ruleForm.oldLeaderId) {
              //移除缓存
              removeCache('CacheToken', true);
              removeCache('userInfo', true);

              //延迟1秒跳转
              setTimeout(function () {
                router.push('/');
              }, 1000);
            } else {
              router.push("/wap/team/index");
            }
          } else {
            ElMessage.error(res.msg);
          }
        }
        );

    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 查询代表队信息
 */
const getTeamInfo = () => {
  baseService
    .get("/front/spteam/1", {})
    .then((res) => {
      if (res.code === 0) {
        let info = res.data;
        if (info) {
          ruleForm.id = info.team.id;
          ruleForm.company = info.team.company;
          ruleForm.provinceName = info.team.province;
          ruleForm.cityName = info.team.city;
          ruleForm.companyNo = info.team.companyNo;
          ruleForm.sex = info.creator.sex + '';
          ruleForm.idType = info.creator.idType;
          ruleForm.idCard = info.creator.idCard;
          ruleForm.phone = info.creator.phone;
          ruleForm.email = info.creator.email;
          ruleForm.realName = info.creator.realName;
          ruleForm.teamName = info.team.teamName;
          ruleForm.header = info.creator.header;
          ruleForm.empower = info.creator.empower;
          ruleForm.oldEmpower = info.creator.empower;
          ruleForm.oldLeaderId = info.team.creator;
          ruleForm.leaderId = info.team.creator;
          imageUrl.value = info.creator.header;
          //imageUrl2.value = info.creator.empower;
          if (info.creator.empower) {
            //判断是否包含后缀为.pdf
            if (info.creator.empower.indexOf('.pdf') != -1) {
              imageUrl2.value = 'http://img.fii-cc.com/fii/20230604/b2f13f0061e14463b63683f3998f055a.jpg';
            } else {
              imageUrl2.value = info.creator.empower;
            }
          }
        }
      }
    }
    );

};

/**
 * 重新认证
 */
const reAuthCompany = () => {
  //校验单位名称不能为空
  if (reAuthForm.company === "") {
    ElMessage.error("单位名称不能为空！");
    return;
  }
  //校验单位代码不能为空
  if (reAuthForm.companyNo === "") {
    ElMessage.error("单位代码不能为空！");
    return;
  }
  reAuthForm.id = ruleForm.id;
  //弹出确认框
  ElMessageBox.confirm('确定更新单位名称吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    reAuthForm.loading = true;
    baseService
      .post("/front/spteam/reAuthCompany", reAuthForm)
      .then((res) => {

   reAuthForm.loading = false;
        if (res.code === 0) {
          ElMessage.success("更新单位名称成功！");
          //关闭弹窗
          reAuthVisible.value = false;
          //刷新页面
          getTeamInfo();
        } else {
          ElMessage.error(res.msg);
        }
      }
      );
  }).catch(() => {
    ElMessage.info('取消更新单位名称');
  });
}


/**
 * 查询用户信息
 * @param formEl
 */
const queryUser = async (formEl: FormInstance | undefined) => {
  //姓名不能为空
  if (ruleForm.realName === "") {
    ElMessage.error("姓名不能为空！");
    return;
  }
  //校验手机号不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号不能为空！");
    return;
  }
  baseService
    .post("/front/spuser/queryUser", {
      realName: ruleForm.realName,
      phone: ruleForm.phone,
      roleId: 0
    })
    .then((res) => {
      if (res.code === 0) {
        ruleForm.idType = res.data.idType;
        ruleForm.idCard = res.data.idCard;
        ruleForm.sex = res.data.sex + '';
        ruleForm.email = res.data.email;
        ruleForm.header = res.data.header;
        ruleForm.leaderId = res.data.id;
        imageUrl.value = res.data.header;
      } else {
        ElMessage.error(res.msg);
      }
    }
    );
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  window.history.go(-1);
};


const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/jpg')) {
    ElMessage.error('仅支持JPG/JPEG/PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('一寸证件照不能超过2MB!')
    return false
  }
  return true
}


const handleAvatarSuccess2: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.empower = response.data.src;
  imageUrl2.value = URL.createObjectURL(uploadFile.raw!)
  if (response.data.showSrc) {
    imageUrl2.value = response.data.showSrc;
  }
}

const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/jpg' || rawFile.type == 'application/pdf')) {
    ElMessage.error('仅支持JPG/JPEG/PNG/PDF格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 100) {
    ElMessage.error('授权书不能超过100MB!')
    return false
  }
  return true
}

getTeamInfo();


</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
